package vy.org.app.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public abstract class BaseAction extends Action {
	
	public final ActionForward execute(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response) {
		try{
			//Initializing context
			ActionCtx actx = ActionCtx.ctx(request);
			String lang = request.getParameter("lang");
			String mnId = request.getParameter(AppConstants.QUERY_PARAM_MENU_ID);
			if(mnId != null){
				request.getSession().setAttribute(AppConstants.SESSION_MENU_ID, mnId);
			}else{
				mnId = (String)request.getSession().getAttribute(AppConstants.SESSION_MENU_ID); 
			}
			
			if(lang == null){
				lang = (String)request.getSession().getAttribute(AppConstants.LANGUAGE);
			}
			if(lang != null){
				actx.setLang(lang);
				request.getSession().setAttribute(AppConstants.LANGUAGE, lang);
			}
			
			if(getModuleId() !=null && getModuleId().getId() != 0 && 
					!actx.getUser().hasAccessToModule(String.valueOf(getModuleId().getId()))){
				return mapping.findForward("illegalaccess");
			}
			
		}catch(SessionExpiredException e){
			//e.printStackTrace();
			return mapping.findForward("sessionexpired");
		}catch(Exception e){
			e.printStackTrace();
			return mapping.findForward("failure");
		}
		
		return executeAction(mapping, actionForm, request, response);
	}
	
	protected abstract ModuleEnum getModuleId();
		
	public abstract ActionForward executeAction(ActionMapping mapping, ActionForm actionForm, 
			HttpServletRequest request, HttpServletResponse response);
	
}
